﻿using System.IO;
using System.Web;
using Google.GData.Client;
using Google.GData.Extensions.MediaRss;
using Google.GData.YouTube;
using Google.YouTube;

namespace uTube.Core.Extensions
{
	public class VideoUploader
	{
		private readonly string _applicationName;
		private readonly string _developerKey;
		private readonly HttpPostedFile _postedFile;
		private readonly string _videoTitle;
		private readonly string _videoDescription;
		private readonly string _keywords;
		private readonly bool _privateVideo;
		private readonly string _category;

		public VideoUploader(string applicationName, string developerKey, HttpPostedFile postedFile, string videoTitle, string videoDescription, string keywords, string category, bool privateVideo)
		{
			this._applicationName = applicationName;
			this._developerKey = developerKey;
			this._postedFile = postedFile;
			this._videoTitle = videoTitle;
			this._videoDescription = videoDescription;
			this._keywords = keywords;
			this._category = category;
			this._privateVideo = privateVideo;
		}

		public string OAuthVideoEntry(string authSubToken)
		{
			YouTubeRequestSettings settings = new YouTubeRequestSettings(this._applicationName, this._developerKey, authSubToken);
			YouTubeRequest request = new YouTubeRequest(settings);

			((GDataRequestFactory)request.Service.RequestFactory).Timeout = 9999999;

			return this.CreateVideoEntry(request);
		}

		public string ClientLoginVideoEntry(string username, string password)
		{
			YouTubeRequestSettings settings = new YouTubeRequestSettings(this._applicationName, this._developerKey, username, password);
			YouTubeRequest request = new YouTubeRequest(settings);

			((GDataRequestFactory)request.Service.RequestFactory).Timeout = 9999999;

			return this.CreateVideoEntry(request);
		}

		private string CreateVideoEntry(YouTubeRequest request)
		{
			Video newVideo = new Video { Title = this._videoTitle, Description = this._videoDescription, Keywords = this._keywords };
			newVideo.Tags.Add(new MediaCategory("Tech", YouTubeNameTable.CategorySchema)); // TODO: Replace hardcoded category with _category
			newVideo.Tags.Add(new MediaCategory("umbraco", YouTubeNameTable.DeveloperTagSchema));
			newVideo.YouTubeEntry.Private = this._privateVideo;

			Stream stream = this._postedFile.InputStream;
			newVideo.YouTubeEntry.MediaSource = new MediaFileSource(stream, this._postedFile.FileName, this._postedFile.ContentType);

			Video createdVideo = request.Upload(newVideo);

			return createdVideo.VideoId;
		}
	}
}